Like any kind of apps, JavaScript apps also have to be written well.
Otherwise, we run into all kinds of issues later on.
In this article, we’ll look at some best practices we should follow when writing Node apps.
Delegate to a Reverse Proxy
We should delegate whatever we can do with a reverse proxy to it.
Things that they can do including SSL, gzip, etc.
This way, our app has to do less, which means it uses fewer resources.
We don’t want our app to be busy doing infrastructural tasks instead of what it’s supposed to do.
Lock Dependencies
To avoid issues with different package versions, we should lock the dependencies of our project.
We can do that by using config files with .npmrc
to tell NPM which exact version is required.
Alternatively, we can use npm shrinkwrap
to lock the dependencies to the ones we want.
Guard Process Uptime Using the Right Tool
We should check for uptime with process management tools like PM2.
This way, our Node app will be restarted if any errors are encountered.
Utilize All CPU Cores
If we have multiple CPU cores in our server, then we should use them all.
We can use Node Cluster or PM2 to manage the clusters for small to medium-sized apps.
For larger apps, we can replicate the process using some Docker cluster or deployment scripts based on Linux’s init system.
Otherwise, we won’t use the full power of our server to serve our app,
Create a Maintenance Endpoint
We can create a maintenance endpoint to return the data that we want to get from the app.
This way, we can get all the information we need in one place.
We don’t want to do diagnostic deploys just to find out some data.
Discover Errors and Downtime using APM Products
APM products are great for finding out errors, downtime, and slow code in our app.
It goes beyond traditional monitoring and monitors the user experience of our app as a whole.
They can find the root cause of performance issues.
Make Our Code Production-Ready
We’ve to plan for production since day 1.
Our app should be stateless. So it shouldn’t save data locally.
A cache should be used anywhere to increase performance.
Memory usage should be checked since the beginning.
We can check for them with tools like memwatch
.
Naming functions help us trace our code when there are any functions.
CI tools are useful for detecting failures before sending our code to production.
Logging data should have contextual information.
And there should be an ID that describes the transaction.
Error handling should be done to prevent crashes.
Measure and Guard Memory Usage
We should make sure that our app don’t use too much memory.
If it does, then we should cap it and make sure our app never uses beyond that amount.
Also, we may gauge memory usage periodically with shell commands for small apps.
But for larger apps, we need to add a built-in memory monitoring system.
Conclusion
We can watch for issues with various monitoring products.
Also, we should all the resources we can get, but keep memory usage in check.